"""
  Copyright (c) 2024 Northeastern University (China)
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
"""
import os
import logging
from ..extractors.extractor import Extractor
from ..extractors.dependency import Dependency
from ..utils.utils import read_lines, read_txt, remove_lstrip

logging.basicConfig()
logger = logging.getLogger(__name__)

    
class MakeExtractor(Extractor):
    def __init__(self, target) -> None:
        super().__init__()
        self.type = 'make'
        self.target = target

    def run_extractor(self):
        self.process_make()

    def process_make(self):
        lines = read_lines(self.target)
        for line in lines:
            line = line.strip()
            if line.startswith('LDLIBS'):
                if '=' not in line:
                    continue
                libs = line.split('=')[1].split(' ')
                for lib in libs:
                    if lib.startswith('-l'):
                        dep_name = remove_lstrip(lib, '-l')
                        dep = Dependency(dep_name, None)
                        dep.add_evidence(self.type, self.target+':'+line, 'High')
                        self.add_dependency(dep)
